package cn.jy.boot.security.filter;

import cn.jy.boot.security.exception.KaptchaMatchException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.IOException;
import java.util.Map;

public class LoginKaptchaSplitFilter extends UsernamePasswordAuthenticationFilter {

    public static final String VERITYCODE_KEY = "kaptcha";

    private String codeParameter = VERITYCODE_KEY;

    public String getCodeParameter() {
        return codeParameter;
    }

    public void setCodeParameter(String codeParameter) {
        this.codeParameter = codeParameter;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //1、判断是否是一个post
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        //2、判断是不是一个json
//        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)){
        //获取session中的验证码
        String sessionCode = (String) request.getSession().getAttribute("code");

            try {
                //3、接收json中的用户名和密码 验证码
                ObjectMapper mapper = new ObjectMapper();
                Map<String,String> userInfo = mapper.readValue(request.getInputStream(),Map.class);
                String username = userInfo.get(getUsernameParameter());
                String password = userInfo.get(getPasswordParameter());
                String requestCode = userInfo.get(getCodeParameter());
                System.out.println(sessionCode);
                //4、判断验证码是否正确
                if( (!ObjectUtils.isEmpty(requestCode)) && (!ObjectUtils.isEmpty(sessionCode)) && (requestCode.equalsIgnoreCase(sessionCode)) ){
                    //5、认证
                    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                    // Allow subclasses to set the "details" property
                    setDetails(request, authRequest);
                    return this.getAuthenticationManager().authenticate(authRequest);
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
//        }
        throw new KaptchaMatchException("验证码错误");
    }
}
